package com.xunkids.bos.migration.component.handler;


import com.xunkids.bos.migration.component.vo.Result;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.AbstractGenericHttpMessageConverter;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * @author lihe
 */
@RestControllerAdvice(basePackages = {"com.xunkids.bos.migration"})
@ConditionalOnClass(RequestMappingHandlerAdapter.class)
public class GlobalControllerWebResultHandler implements ResponseBodyAdvice<Object> {

    private final String WEB_RESULT_CLASS_NAME = Result.class.getName();

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        if (!AbstractGenericHttpMessageConverter.class.isAssignableFrom(converterType)) {
            return false;
        }
        String typeName = returnType.getGenericParameterType().getTypeName().split("<")[0];
        return !WEB_RESULT_CLASS_NAME.equals(typeName);

    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        return Result.ok(body);
    }

}